﻿using System.Collections.Generic;
using SlamCms.Common;

namespace SlamCms.Web.Sitemaps
{
	public class SitemapNode
	{
		private string _url;
		private int _depth;

		public SitemapNode()
		{
			this.Properties = new Dictionary<string, object>();
			this.Children = new List<SitemapNode>();
		}

		public string Key { get; set; }
		public string Title { get; set; }

		public string Url
		{
			get
			{
				return _url;	
			} 

			set
			{
				Ensure.PropertyNotNull(value);
				_url = value;
			}
		}

		public int Depth
		{
			get
			{
				if (_depth <= 0)
				{
					var count = 1;
					var node = Parent;

					while (node != null)
					{
						count++;
						node = node.Parent;
					}

					_depth = count;
				}

				return _depth;
			}
		}

		public IDictionary<string, object> Properties { get; set; }

		public SitemapNode Parent { get; set; }
		public IList<SitemapNode> Children { get; set; }

		public SitemapNode AddChild(SitemapNode childNode)
		{
			this.Children.Add(childNode);
			return this;
		}

		public IEnumerable<SitemapNode> GetBreadcrumb(bool includeCurrentNode = true)
		{
			var list = new List<SitemapNode>();

			var node = this;

			if (includeCurrentNode)
				list.Add(node);

			node = node.Parent;

			while (node != null)
			{
				list.Add(node);
				node = node.Parent;
			}

			list.Reverse();

			return list;
		}

		public SitemapNode Clone(SitemapNode newParent)
		{
			var cloned = new SitemapNode()
			{
				Key = this.Key,
				Parent = this.Parent,
				Properties = new Dictionary<string, object>(this.Properties),
				Title = this.Title,
				Url = this.Url
			};

			foreach (var child in this.Children)
				cloned.AddChild(child.Clone(cloned));

			return cloned;
		}

		public override string ToString()
		{
			return "{0} [{1}]".F(Title, Url);
		}
	}
}